#include "GraphicsView.h"

GraphicsView::GraphicsView(QWidget *parent) : QGraphicsView(parent)
{
    currentRectNum = 0;
    maxRectsNum = 3;
    mouseEnabled = false;

    rects.reserve(3);
    rectsPoints.reserve(6);

    for(int i = 0; i < 3; ++i)
        rects[i] = new QGraphicsRectItem();
}

void GraphicsView::mouseReleaseEvent(QMouseEvent *event)
{
    if(mouseEnabled) {
        if(currentRectNum != maxRectsNum) {
            if(point1.isNull()) {
                point1.setX(event->x());
                point1.setY(event->y());

                rectsPoints.push_back(point1);
            }
            else {
                point2.setX(event->x());
                point2.setY(event->y());

                rectsPoints.push_back(point2);

                int width = point2.x() - point1.x();
                int height = point2.y() - point1.y();

                rects[currentRectNum]->setRect(point1.x(), point1.y(), width, height);
                rects[currentRectNum]->setPen(QPen(Qt::red));
                scene()->addItem(rects[currentRectNum]);

                point1.setX(0);
                point1.setY(0);
                ++currentRectNum;
            }
        }
    }

    event->accept();
}

void GraphicsView::resetRects()
{
    for(int i = 0; i < currentRectNum; ++i)
        scene()->removeItem(rects[i]);

    currentRectNum = 0;
    rectsPoints.clear();
}
